//
//  QRCodeSignViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/3/7.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "QRCodeSignViewController.h"
#import "ManualSignViewController.h"

@interface QRCodeSignViewController () <AVCaptureMetadataOutputObjectsDelegate>
{
    BOOL  changed;
}

@property (weak, nonatomic) IBOutlet UIImageView *statusImv;
@property (weak, nonatomic) IBOutlet UILabel *statusLab;
@property (weak, nonatomic) IBOutlet UILabel *detailLab;
@property (weak, nonatomic) IBOutlet UILabel *unSignLab;
@property (weak, nonatomic) IBOutlet UILabel *signedLab;
@property (weak, nonatomic) IBOutlet UIView *lineView;

@property (weak, nonatomic) IBOutlet UIButton *continueSignBtn;
@property (weak, nonatomic) IBOutlet UIButton *manualSignBtn;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *layer;

@end

@implementation QRCodeSignViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"签到";
    
    self.continueSignBtn.layer.cornerRadius = 4.;
    self.continueSignBtn.layer.masksToBounds = YES;
    [self.continueSignBtn  addTarget:self action:@selector(continueSignButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.manualSignBtn.layer.cornerRadius = 4.;
    self.manualSignBtn.layer.masksToBounds = YES;
    [self.manualSignBtn  addTarget:self action:@selector(manualSignButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.backBtn.layer.cornerRadius = 4.;
    self.backBtn.layer.masksToBounds = YES;
    [self.backBtn  addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.backBtn.hidden = YES;
    self.continueSignBtn.hidden = YES;
    self.manualSignBtn.hidden = YES;
    
    self.statusLab.text = @"";
    self.detailLab.text = @"";
    self.unSignLab.text = @"";
    self.signedLab.text = @"";
    self.lineView.hidden = YES;
    
    changed = NO;
    [self  requestQRSignFirstFailed];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (changed) {
        [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshCourseList" object:nil];
    }
    
    if (self.session) {
        [self.session stopRunning];
        self.session = nil;
    }
    
    if (self.layer) {
        [self.layer removeFromSuperlayer];
        self.layer = nil;
    }
}

- (void)continueSignButtonClick
{
    [self  startScanning];
}

- (void)manualSignButtonClick
{
    ManualSignViewController  *viewController = [[ManualSignViewController  alloc] initWithNibName:@"ManualSignViewController" bundle:nil];
    viewController.classNameStr = [NSString  stringWithFormat:@"%@",self.className];
    viewController.scheduleIdStr = [NSString  stringWithFormat:@"%@",self.scheduleId];
    [self.navigationController  pushViewController:viewController animated:YES];
}

- (void)backButtonClick
{
    [self.navigationController  popViewControllerAnimated:YES];
}

- (NSMutableAttributedString *)createattributedStr:(NSString  *)string
{
    NSMutableAttributedString  *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle  *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8.];
    paragraphStyle.alignment = NSTextAlignmentCenter;
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    [attributedString  addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
    
    return attributedString;
}

#pragma mark - 网络相关
#pragma mark 扫码签到
- (void)sendQRSignRequestWithStr:(NSString  *)string
{
    if (!string) {
        return;
    }
    [self  showHudithString:@"加载中..."];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:
                               [NSString  stringWithFormat:@"%@",self.scheduleId],@"id",
                               [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"teacherId",
                               [NSString  stringWithFormat:@"%@",string],@"stuNumber",
                               nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIPPT@"teacher/scanSign.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            changed = YES;
            NSDictionary  *resultDic = [responseObject  objectForKey:@"result"];
            self.statusImv.image = [UIImage  imageNamed:@"QRSign_Scuess"];
            self.statusLab.text = [NSString  stringWithFormat:@"%@",[resultDic  objectForKey:@"title"]];
            self.detailLab.text = @"";
            NSArray  *noSignName = [resultDic  objectForKey:@"noSignName"];
            NSArray  *signName = [resultDic  objectForKey:@"signName"];
            NSString  *signNameStr = @"";
            if (signName.count > 0) {
                signNameStr = [NSString  stringWithFormat:@"%@",[signName  componentsJoinedByString:@"  "]];
            }
            if (!noSignName || noSignName.count == 0) {
                self.unSignLab.attributedText = [self  createattributedStr: [NSString  stringWithFormat:@"%@\n%@",[resultDic  objectForKey:@"signText"],signNameStr]];
                self.signedLab.text = @"";
                self.lineView.hidden = YES;
                
                self.backBtn.hidden = NO;
                self.continueSignBtn.hidden = YES;
                self.manualSignBtn.hidden = YES;
                
            }else {
                NSString  *noSignNameStr = [NSString  stringWithFormat:@"%@",[noSignName  componentsJoinedByString:@"  "]];
                self.unSignLab.attributedText = [self  createattributedStr:[NSString  stringWithFormat:@"%@\n%@",[resultDic  objectForKey:@"noSignText"],noSignNameStr]];
                if (signNameStr.length > 0) {
                    self.signedLab.attributedText = [self  createattributedStr:[NSString  stringWithFormat:@"%@\n%@",[resultDic  objectForKey:@"signText"],signNameStr]];
                }else {
                    self.signedLab.attributedText = [self  createattributedStr:[NSString  stringWithFormat:@"%@\n暂无学生签到",[resultDic  objectForKey:@"signText"]]];
                }
                self.lineView.hidden = NO;
                
                self.backBtn.hidden = YES;
                self.continueSignBtn.hidden = NO;
                self.manualSignBtn.hidden = NO;
            }
            
        }else {
            self.statusImv.image = [UIImage  imageNamed:@"QRSign_Failed"];
            self.statusLab.text = @"签到失败";
            self.detailLab.text = @"请检查班级或学生二维码是否正确";
//            self.unSignLab.text = @"";
//            self.signedLab.text = @"";
//            self.lineView.hidden = YES;
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark 扫码签到第一次失败后调用
- (void)requestQRSignFirstFailed
{
    [self  showHudithString:@"发送中..."];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:
                               [NSString  stringWithFormat:@"%@",self.scheduleId],@"id",
                               [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"teacherId",
                               nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIPPT@"teacher/scanSignFirst.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            NSDictionary  *resultDic = [responseObject  objectForKey:@"result"];
            NSArray  *noSignName = [resultDic  objectForKey:@"noSignName"];
            NSArray  *signName = [resultDic  objectForKey:@"signName"];
            NSString  *signNameStr = @"";
            if (signName.count > 0) {
                signNameStr = [NSString  stringWithFormat:@"%@",[signName  componentsJoinedByString:@"  "]];
            }
            if (!noSignName || noSignName.count == 0) {
                self.unSignLab.attributedText = [self  createattributedStr:[NSString  stringWithFormat:@"%@\n%@",[resultDic  objectForKey:@"signText"],signNameStr]];
                self.signedLab.text = @"";
                self.lineView.hidden = YES;
                
                self.backBtn.hidden = NO;
                self.continueSignBtn.hidden = YES;
                self.manualSignBtn.hidden = YES;
                
                self.statusImv.image = [UIImage  imageNamed:@"QRSign_Scuess"];
                self.statusLab.text = @"所有同学签到成功";
//                self.detailLab.text = @"请检查班级或学生二维码是否正确";
            }else {
                NSString  *noSignNameStr = [NSString  stringWithFormat:@"%@",[noSignName  componentsJoinedByString:@"  "]];
                self.unSignLab.attributedText = [self  createattributedStr:[NSString  stringWithFormat:@"%@\n%@",[resultDic  objectForKey:@"noSignText"],noSignNameStr]];
                if (signNameStr.length > 0) {
                    self.signedLab.attributedText = [self  createattributedStr:[NSString  stringWithFormat:@"%@\n%@",[resultDic  objectForKey:@"signText"],signNameStr]];
                }else {
                    self.signedLab.attributedText = [self  createattributedStr:[NSString  stringWithFormat:@"%@\n暂无学生签到",[resultDic  objectForKey:@"signText"]]];
                }
                self.lineView.hidden = NO;
                
                self.backBtn.hidden = YES;
                self.continueSignBtn.hidden = NO;
                self.manualSignBtn.hidden = NO;
                
                [self  startScanning];
            }
            
        }else {
            self.unSignLab.text = @"";
            self.signedLab.text = @"";
            self.lineView.hidden = YES;
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

- (void)startScanning
{
    if (!self.session) {
        // 1.创建捕捉会话
        self.session = [[AVCaptureSession alloc] init];
        
        // 2.添加输入设备(数据从摄像头输入)
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
        [self.session addInput:input];
        
        // 3.添加输出数据(示例对象-->类对象-->元类对象-->根元类对象)
        AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
        [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        //    [output setRectOfInterest:CGRectMake((124)/SCREEN_HEIGHT,((SCREEN_WIDTH-220)/2)/SCREEN_WIDTH,220/SCREEN_HEIGHT,220/SCREEN_WIDTH)];
        [self.session addOutput:output];
        
        // 3.1.设置输入元数据的类型(类型是二维码数据)
        [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    }
    
    // 4.添加扫描图层
    if (self.layer) {
        [self.layer removeFromSuperlayer];
        self.layer = nil;
    }
    self.layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.layer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    [self drawImage];
    [self.view.layer  addSublayer:self.layer];
    
    // 5.开始扫描
    [self.session startRunning];
}

//摄像机layer添加半透明的layer
- (void)drawImage{
    CALayer * imageLayer = [CALayer layer];
    //层的  大小
    imageLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
    //设置剪辑
    imageLayer.masksToBounds = YES;
    //加载图片
    imageLayer.contents = (id)[UIImage imageNamed:@"扫码框"].CGImage;
    
    [self.layer addSublayer:imageLayer];
}

#pragma mark - AVCaptureMetadataOutputObjects Delegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        //获得扫描数据，最后一个时最新扫描的数据
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        NSString  *resultStr = [object stringValue];
        [self  sendQRSignRequestWithStr:resultStr];
        
        [self.session stopRunning];
        // 将预览图层移除
        [self.layer removeFromSuperlayer];
        self.layer = nil;
    }else {
        [ZPPromptView  showMessage:@"没有扫描到数据"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
